package com.luoruihang.logstatementgenerator.domain.infrastructure.http;

import cn.hutool.jwt.JWT;
import com.luoruihang.logstatementgenerator.domain.infrastructure.database.LlmSource;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class LlmJwtUtil {
	public static String token() {
		String token = "";
		String[] idAndSecret = LlmSource.apiKey.split("\\.");
		String id = idAndSecret[0];
		String secret = idAndSecret[1];

		// 设置头部信息
		Map<String, Object> header = new HashMap<>();
		header.put("alg", "HS256");
		header.put("sign_type", "SIGN");
		// 设置payload信息
		Map<String, Object> payload = new HashMap<>();
		payload.put("api_key", id);
		long curTime = new Date().getTime();
		payload.put("exp", curTime + 1000000);
		payload.put("timestamp", curTime);
		// 签名生成
		token = JWT.create()
			.addHeaders(header)
			.addPayloads(payload)
			.setKey(secret.getBytes())
			.sign();
		return token;
	}

	public static boolean verifyToken(String token) {
		String secret = LlmSource.apiKey.split("\\.")[1];
		return JWT.of(token).setKey(secret.getBytes()).verify();
	}
}
